package org.bees.cms.core.clause;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.bees.cms.core.Specific;

@Entity
public class Aggregation extends Clause implements Specific<String> {
	private static final long serialVersionUID = -4951340425531005146L;

	private String[] properties;
	private Criterion meet;

	@Override
	public String toSQL(Adapter adapter, Class<?> mapper, String alias) throws Exception {
		StringBuilder builder = new StringBuilder();
		for (int i = 0; properties != null && i < properties.length; i++) {
			builder.append(" ").append(adapter.adapt(mapper, properties[i], alias));
		}
		return builder.toString().trim().equals("") ? "" : "GROUP BY" + builder.toString() + (meet == null ? "" : " " + meet.toSQL(adapter, mapper, alias));
	}

	@Transient
	@Column(name = "particular")
	public String[] getProperties() {
		return properties;
	}

	public void setProperties(String[] properties) {
		this.properties = properties;
	}

	@ManyToOne(cascade = { CascadeType.REFRESH })
	public Criterion getMeet() {
		return meet;
	}

	public void setMeet(Criterion meet) {
		this.meet = meet;
	}

	@Column(length = 200)
	@Override
	public String getParticular() throws Exception {
		JSONArray array = new JSONArray();
		for (int i = 0; properties != null && i < properties.length; i++) {
			JSONObject object = new JSONObject();
			object.accumulate("property", properties[i]);
			array.add(object);
		}
		return array.toString();
	}

	@Override
	public void setParticular(String particular) throws Exception {
		JSONArray array = JSONArray.fromObject(particular);
		properties = new String[array.size()];
		for (int i = 0; i < array.size(); i++) {
			properties[i] = array.getJSONObject(i).getString("property");
		}
	}

}
